from exporters.exporter import *
from sheetReader import *

class JsonValueExporter:
	def Export(value):
		return value

class JsonIntExporter(JsonValueExporter):
	def Export(value):
		return str(int(float(value)))

class JsonFloatExporter(JsonValueExporter):
	def Export(value):
		return str(float(value))

class JsonStringExporter(JsonValueExporter):
	def Export(value):
		return "\"" + value + "\""

class JsonExporter(Exporter):
	def Export(self, sheet):
		sb = []
		sb.append("{\n")

		configMap = sheet.GetConfigMap()
		self.ExportMap(sb, "\t", configMap)
		sb.pop()
		listKey = list(configMap.keys())
		config = configMap[listKey[0]]
		subConfig = config[list(config.keys())[0]]
		if (type(subConfig) == dict):
			sb.append("\t}\n")
		else:
			sb.append("}\n")
		sb.append("}")
		return "".join(sb)

	def ExportMap(self, sb, prefix, configMap):
		listKey = list(configMap.keys())
		keyCount = len(listKey)
		for i in range(0, keyCount):
			key = listKey[i]
			config = configMap[key]
			if (type(config) == dict):
				if key.valueType == ValueType.StringValue:
					newPrefix = prefix + self.ExportValue(key.value, key.valueType)
				else:
					newPrefix = prefix + "\"" + self.ExportValue(key.value, key.valueType) + "\""
				subConfig = config[list(config.keys())[0]]
				if (type(subConfig) == dict):
					sb.append(newPrefix + ": {\n")
				else:
					sb.append(newPrefix + ": ")
				self.ExportMap(sb, prefix + "\t", config)
				if (type(subConfig) == dict):
					sb.pop()
					sb.append("}\n")
					sb.append(prefix + "},\n")
			else:
				if (i == 0):
					sb.append("{")
				sb.append("\"" + key + "\": " + self.ExportValue(config.value, config.valueType))
				if (i < keyCount - 1):
					sb.append(", ")
				if (i == keyCount - 1):
					sb.append("},\n")

	def ExportValue(self, value, valueType):
		if (valueType == ValueType.SrcValue):
			return JsonValueExporter.Export(value)
		if (valueType == ValueType.IntValue):
			return JsonIntExporter.Export(value)
		if (valueType == ValueType.FloatValue):
			return JsonFloatExporter.Export(value)
		if (valueType == ValueType.StringValue):
			return JsonStringExporter.Export(value)